<template>
  <img :src="myplaneImg" :style="planeStyle" />
</template>

<script>
import { computed, onMounted, onUnmounted, reactive, watch } from "vue";
import myplaneImg from "../assets/plane.png";
import useKeyboard from "../utils/useKeyboard";

const useAttack = (data, context) => {
  let isAttack = false;
  let timer = null;
  const attack = () => {
    const bulletData = {
          x: data.x + 27.5,
          y: data.y,
        };
        context.emit("attack", bulletData);
  }
  onMounted(() => {
    timer = setInterval(() => {
      // console.log(isAttack)
      // console.log(11111111)
      if (isAttack) {
        // console.log('fashe')
        attack()
      }
    }, 200);
  });
  onUnmounted(() => {
    clearInterval(timer);
    timer = null;
  });
  const start = () => {
    if (!isAttack) {
      // console.log("点射")   可以不加if包裹
      attack()
    }
    isAttack = true;
  };
  const stop = () => {
    isAttack = false;
  };

  useKeyboard({
    Space: {
      keydown: start,
      keyup: stop,
    },
  });
};
export default {
  name: "Myplane",
  props: ["x", "y"],
  setup(props, context) {
    const data = reactive({
      x: props.x,
      y: props.y,
    });

    const planeStyle = computed(() => {
      return {
        left: data.x + "px",
        top: data.y + "px",
      };
    });

    watch(props, (newVal) => {
      data.x = newVal.x;
      data.y = newVal.y;
    });

    useAttack(data, context);

    return { myplaneImg, planeStyle };
  },
};
</script>

<style lang="stylus" scoped>
img {
  position: absolute;
  width: 20%;
}
</style>